<template>
  <a-spin :spinning="loading" class="w-full pt-40 min-h-[300px]">
    <a-form v-if="!loading" :model="formState" class="form-style-flex overflow-auto" :class="formClass" :label-col="{ style: { width: '100px' } }">
      <a-form-item label="姓名" :class="itemClass || 'w-1/3'" required>
        <SelectTable
          v-model:value="formState.brName"
          :type="patientType"
          custom-input
          :maxlength="20"
          :table-width="tableWidth"
          :search-params="searchParams"
          empty-close
          @input-change="getPinyin"
          @select="onSelectPatient"
        />
      </a-form-item>
      <a-form-item label="病历卡号" :class="itemClass || 'w-1/3'">
        <span>：{{ formState.brBlkh || '-' }}</span>
      </a-form-item>
      <a-form-item label="助记码" :class="itemClass || 'w-1/3'" required>
        <a-input v-model:value="formState.pyjm" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="住院号" :class="itemClass || 'w-1/3'" required :disabled="true">
        <a-input v-model:value="formState.admissionCode" class="w-3/4" placeholder="请输入" :disabled="isDisabledZyh" />
        <a-button type="link" class="w-1/4 px-2" :disabled="isDisabledZyh" @click="generatedZyh">生成</a-button>
      </a-form-item>
      <a-form-item label=" " :class="itemClass || 'w-1/3'">
        <a-radio-group v-model:value="formState.brXb">
          <a-radio value="男">男</a-radio>
          <a-radio value="女">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <div v-show="openAll" class="flex flex-wrap">
        <template v-for="item in itemConfig" :key="item.label">
          <a-form-item
            v-if="showConfig[item.label]"
            :label="item.label"
            :class="item.className || itemClass"
            :required="item.required"
            :label-col="{ style: { width: item.labelCol ? item.labelCol : '100px' } }"
          >
            <a-input v-if="item.label === '证件号码'" v-model:value="formState.brSfz" v-input:idcard placeholder="请输入" @blur="onIdCardBlur" />
            <a-input v-else-if="item.label === '年龄' && item.format === 'string'" v-model:value="formState.brAge" placeholder="请输入">
              <template #addonAfter>
                <a-select v-model:value="formState.ageUnit" style="width: 60px">
                  <a-select-option value="岁">岁</a-select-option>
                  <a-select-option value="月">月</a-select-option>
                  <a-select-option value="天">天</a-select-option>
                </a-select>
              </template>
            </a-input>
            <a-input
              v-else-if="
                item.type === 'input' &&
                item.value !== 'brJtdz' &&
                item.value !== 'brHkdz' &&
                item.value !== 'brJg' &&
                item.value !== 'brCsd' &&
                item.value !== 'brLxrdz'
              "
              v-model:value="formState[item.value]"
              placeholder="请输入"
            />
            <template v-if="item.value === 'brJtdz'">
              <SelectAddress v-model:value="formState.provincesCityDistrict" allow-clear class="!w-1/2 pr-2" />
              <a-input v-model:value="formState[item.value]" class="w-1/2" placeholder="请输入详细地址" />
            </template>
            <template v-if="item.value === 'brJg'">
              <SelectAddress v-model:value="formState.brJg" allow-clear />
            </template>
            <template v-if="item.value === 'brCsd'">
              <SelectAddress v-model:value="formState.brCsd" allow-clear />
            </template>
            <template v-if="item.value === 'brHkdz'">
              <SelectAddress v-model:value="formState.hkProvincesCityDistrict" allow-clear class="!w-1/2 pr-2" />
              <a-input v-model:value="formState[item.value]" class="w-1/2" placeholder="请输入户籍地址" />
            </template>
            <template v-if="item.value === 'brLxrdz'">
              <SelectAddress v-model:value="formState.lxrProvincesCityDistrict" allow-clear class="!w-1/2 pr-2" />
              <a-input v-model:value="formState[item.value]" class="w-1/2" placeholder="请输入户籍地址" />
            </template>
            <a-date-picker
              v-else-if="item.type === 'date'"
              v-model:value="formState[item.value]"
              placeholder="请选择"
              value-format="YYYY-MM-DD"
              @change="onDateChange(item.label)"
            />
            <SelectItem
              v-else-if="item.type === 'selectItem'"
              v-model:value="formState[item.value]"
              value-key="dictItemName"
              :type="item.code"
              trigger="init"
              placeholder="请选择"
            />
            <SelectTags
              v-else-if="item.type === 'selectTags'"
              v-model:value="formState[item.value]"
              show-setting
              show-new
              type="医嘱字典"
              :multiple="item.multiple"
              :search-params="{ blcybh: item.label }"
              placeholder="请选择"
            />
            <!-- 过敏史 -->
            <SelectAllergyModal
              v-else-if="item.type === 'selectAllergy'"
              v-model:value="formState[item.value]"
              :br-id="formState.brId"
              :source-data="formState.patientAllergys"
              @success="formState.patientAllergys = $event.data"
            />
          </a-form-item>
        </template>
        <!-- 收费标准 -->
        <a-form-item v-if="!excludeItem.includes('收费标准') && getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1'" label="收费标准" class="w-1/2">
          <SelectChargeStandard v-model:value="formState.chargeStandardId" select-first />
        </a-form-item>
        <a-form-item v-if="showConfig['备注']" label="备注" class="w-full">
          <a-input v-model:value="formState.cmemo" placeholder="请输入" />
        </a-form-item>
        <a-divider v-if="showDividerBotInfo" dashed />
        <div v-if="showDividerBotInfo" class="mt-2">
          <div class="flex flex-wrap">
            <a-form-item label="业务员" class="w-1/3">
              <SelectTable v-model:value="formState.brYwyName" type="员工" @select="onSelectEmployee('brYwy', $event)" />
            </a-form-item>
            <a-form-item label="咨询师" class="w-1/3">
              <SelectTable v-model:value="formState.brZxsName" type="员工" :search-params="{ emplbid: '14' }" @select="onSelectEmployee('brZxs', $event)" />
            </a-form-item>
            <a-form-item label="负责人" class="w-1/3">
              <SelectTable v-model:value="formState.brFzrName" type="员工" @select="onSelectEmployee('brFzr', $event)" />
            </a-form-item>
            <a-form-item label="关注项目" class="w-full">
              <SelectFocusProject v-model:value="formState.brZlxm" placeholder="请选择" />
            </a-form-item>
            <a-form-item label="客户来源" class="w-full">
              <SelectCustomerSource v-model:value="formState.brly" />
            </a-form-item>
            <a-form-item label="客户标签" class="w-full">
              <CustomerLabel :br-id="formState.brId" />
            </a-form-item>
          </div>
        </div>
      </div>
    </a-form>
    <!-- <div v-if="!loading" class="flex justify-center">
      <span v-if="openAll" class="cursor-pointer" @click="openAll = false">收起<up-outlined /></span>
      <span v-else class="cursor-pointer" @click="openAll = true">展开<down-outlined /></span>
    </div> -->
    <!-- <TagsModal v-model:open="openTagsModal" :tag-data="tagsList" @success="onSelectTags" /> -->
  </a-spin>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
// import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import { post } from '@/utils/request'
import SelectItem from '@/components/SelectItem'
import SelectTable from '@/components/SelectTable'
import { getSystemConfig } from '@/utils/systemConfig'
import CustomerLabel from '@/components/CustomerLabel'
import SelectAllergyModal from '@/components/SelectAllergy'
import SelectFocusProject from '@/components/SelectFocusProject'

const emit = defineEmits(['change', 'update:value', 'loaded'])
const props = defineProps({
  value: {
    type: Object,
    default: () => ({})
  },
  patientInfo: {
    type: Object,
    default: () => ({})
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  patientType: {
    type: String,
    default: '患者'
  },
  tableWidth: {
    type: Number,
    default: 620
  },
  itemClass: {
    desc: '表单项样式',
    type: String,
    default: 'w-1/2'
  },
  formClass: {
    desc: '表单样式',
    type: String,
    default: ''
  },
  searchParams: {
    desc: '搜索条件',
    type: Object,
    default: () => ({})
  },
  excludeItem: {
    desc: '排除的字段',
    type: Array,
    default: () => []
  },
  showDividerBotInfo: {
    desc: '是否显示底部信息',
    type: Boolean,
    default: () => true
  }
})

const loading = ref(true)
const openAll = ref(true)
const itemConfig = [
  { label: '证件类型', value: 'brZjlx', type: 'selectItem', code: 'DT00001' },
  { label: '证件号码', value: 'brSfz', type: 'input' },
  { label: '出生日期', value: 'brBtd', type: 'date' },
  { label: '年龄', value: 'brAge', type: 'input', format: 'string', required: true },
  // { label: '(年龄不足1周岁) 年龄', value: 'brBzAge', type: 'input' },
  { label: '手机号', value: 'brMob', type: 'input' },
  { label: '婚姻状况', value: 'brHf', type: 'selectItem', code: 'DT00002' },
  { label: '电话', value: 'brJtdh', type: 'input' },
  { label: '邮件', value: 'brEmail', type: 'input' },
  { label: '家庭地址', value: 'brJtdz', type: 'input', className: 'w-full', required: true },
  { label: '户籍地址', value: 'brHkdz', type: 'input', className: 'w-full' },
  { label: '邮编', value: 'brJtpostno', type: 'input' },
  { label: '民族', value: 'brMz', type: 'selectItem', code: 'naty' }, //DT00003
  { label: '国籍', value: 'brGj', type: 'selectItem', code: 'DT00004' },
  // { label: '户籍', value: 'brJg', type: 'input' },
  { label: '籍贯', value: 'brJg', type: 'input', required: true },
  { label: '新生儿出生体重', value: 'brXsecstz', type: 'input', suffix: 'cm', format: 'number', labelCol: '120px' },
  { label: '新生儿入院体重', value: 'brXserytz', type: 'input', suffix: 'kg', format: 'number', labelCol: '120px' },
  { label: '出生地', value: 'brCsd', type: 'input' },
  { label: '身高', value: 'brSg', type: 'input', suffix: 'cm' },
  { label: '体重', value: 'brTz', type: 'input', suffix: 'kg' },
  { label: '文化程度', value: 'brWhcd', type: 'selectItem', code: 'DT00005' },
  { label: '血型', value: 'brXx', type: 'selectItem', code: 'DT00006' },
  { label: 'RH', value: 'rhxx', type: 'selectItem', code: 'DT00007' },
  { label: '人员属性', value: 'rysx', type: 'selectItem', code: 'DT00021' },
  { label: '联系人', value: 'brLxr', type: 'input' },
  { label: '联系人关系', value: 'brLxrgx', type: 'selectItem', code: 'DT00008' },
  { label: '联系人电话', value: 'brLxrdh', type: 'input' },
  { label: '联系人地址', value: 'brLxrdz', type: 'input', className: 'w-full' },
  { label: '职业', value: 'brZy', type: 'selectItem', code: 'DT00009' },
  { label: '工作单位', value: 'brGzdw', type: 'input' },
  { label: '单位电话', value: 'brDwdh', type: 'input' },
  // { label: '工作邮编', value: 'xxxxx', type: 'input' },
  { label: '工作地址', value: 'brGzdz', type: 'input' },
  { label: '政治面貌', value: 'brZzmm', type: 'selectItem', code: 'DT00010' },
  { label: '入伍日期', value: 'brRwny', type: 'date' },
  { label: '部队番号', value: 'brBdfh', type: 'input' },
  { label: '部别', value: 'brBb', type: 'input' },
  { label: '军种', value: 'brJz', type: 'selectItem', code: 'DT00022' },
  { label: '军衔', value: 'brJx', type: 'selectItem', code: 'DT00023' },
  { label: '既往史', value: 'brJws', type: 'selectTags', multiple: true, className: 'w-full' },
  { label: '过敏史', value: 'brGms', type: 'selectAllergy', multiple: true, className: 'w-full' },
  { label: '遗传史', value: 'brYcs', type: 'selectTags', className: 'w-full' },
  { label: '家族史', value: 'brJzs', type: 'selectTags', className: 'w-full' },
  { label: '月经及生育史', value: 'brYjsjsys', type: 'selectTags', className: 'w-full' },
  { label: '暴露史', value: 'brBls', type: 'selectTags', className: 'w-full' },
  { label: '残疾情况', value: 'brCjqk', type: 'selectTags', className: 'w-full' },
  { label: '职业病', value: 'brZyb', type: 'selectItem', className: 'w-full', code: 'DT00011' }
]
const formState = ref({
  brName: '',
  brXb: '男',
  brSfz: '',
  brMob: '',
  brLxrdz: '',
  brZjlx: '',
  brBtd: '',
  brAge: '',
  brHf: '',
  brJtdz: '',
  brJtpostno: '',
  ageUnit: '岁'
})

const onIdCardBlur = async () => {
  const idCard = formState.value.brSfz
  if (formState.value.brZjlx && formState.value.brZjlx === '身份证') {
    if (idCard.length === 18 || idCard.length === 16) {
      const { code, data, msg } = await post('/common/util/getCsrq', { sfzhm: idCard })
      if (code !== 0) return message.error(msg || '身份证有误')
      formState.value.brBtd = data.brBtd
      formState.value.brAge = data.brAge
      formState.value.brXb = data.brXb
      formState.value.ageUnit = calculateAgeUnit(formState.value.brBtd) || '岁'
    }
  }
}
const isDisabledZyh = ref(false)

const onSelectPatient = (select) => {
  if (getSystemConfig('INP_NO_BINIDNG_PATIENT') === '0' && props.patientType === '入院登记') {
    select.admissionCode = ''
    isDisabledZyh.value = false
  }
  if (getSystemConfig('INP_NO_BINIDNG_PATIENT') === '1' && props.patientType === '入院登记') {
    isDisabledZyh.value = select.admissionCode
  }
  formState.value = {
    ...select,
    brAge: getAgeUnit(select.brAge)?.brAge,
    ageUnit: getAgeUnit(select.brAge)?.ageUnit || '岁'
  }
  emit('change', {
    ...select,
    brAge: getAgeUnit(select.brAge)?.brAge,
    ageUnit: getAgeUnit(select.brAge)?.ageUnit || '岁'
  })
}
watch(
  () => props.rowData,
  (val) => {
    if (val) {
      if (getSystemConfig('INP_NO_BINIDNG_PATIENT') === '0' && props.patientType === '入院登记') {
        emit('update:value', { ...props.value, admissionCode: '' })
        isDisabledZyh.value = false
      }
      if (getSystemConfig('INP_NO_BINIDNG_PATIENT') === '1' && props.patientType === '入院登记') {
        isDisabledZyh.value = !!val.admissionCode
      }
    }
  },
  {
    immediate: true
  }
)
const onDateChange = (label) => {
  if (label === '出生日期' && formState.value.brZjlx === '身份证' && formState.value.brSfz) {
    //身份证出生日期
    const idCardBrd = extractBirthdateFromId(formState.value.brSfz)
    if (formState.value.brBtd !== idCardBrd) {
      message.warn('证件号码与出生日期不一致，请核对')
    }
  }
  if (label === '出生日期' && !formState.value.brSfz) {
    formState.value.brAge = calculateAge(formState.value.brBtd) || 0
    formState.value.ageUnit = calculateAgeUnit(formState.value.brBtd) || '岁'
  }
}
// 正则表达式匹配身份证号码中的出生日期部分（6到14位）
const extractBirthdateFromId = (id) => {
  const regex = /^(\d{6})(\d{8})(\w*)$/
  const match = id.match(regex)

  if (match) {
    // 提取出生日期部分并转换为年-月-日的格式
    const birthdate = `${match[2].slice(0, 4)}-${match[2].slice(4, 6)}-${match[2].slice(6, 8)}`
    return birthdate
  } else {
    return message.warn('无效的身份证号码')
  }
}
//根据日期计算年龄
const calculateAge = (birthDate) => {
  const today = new Date()
  const birthDay = new Date(birthDate)
  const timeDiff = Math.abs(today.getTime() - birthDay.getTime())
  const day = Math.round(timeDiff / (24 * 60 * 60 * 1000))
  if (day <= 365) {
    if (day <= 30) {
      return day
    } else {
      return Math.floor(day / 30)
    }
  } else {
    return Math.floor(day / 365)
  }
}
//根据日期计算年龄单位
const calculateAgeUnit = (birthDate) => {
  const today = new Date()
  const birthDay = new Date(birthDate)
  const timeDiff = Math.abs(today.getTime() - birthDay.getTime())
  const day = Math.round(timeDiff / (24 * 60 * 60 * 1000))
  if (day <= 365) {
    if (day <= 30) {
      return '天'
    } else {
      return '月'
    }
  } else {
    return '岁'
  }
}
//分别取出年龄数值和年龄单位
const getAgeUnit = (val) => {
  if (!val) return { brAge: '', ageUnit: '' }
  const charsToCheck = ['岁', '月', '天']
  const result = charsToCheck.some((char) => String(val).includes(char))
  if (result) {
    return { brAge: val.substring(0, val.length - 1), ageUnit: val.substring(val.length - 1) }
  } else {
    return { brAge: val, ageUnit: '岁' }
  }
}
watch(
  () => props.value.brName,
  () => {
    formState.value = { ...props.value, brAge: getAgeUnit(props.value.brAge)?.brAge, ageUnit: getAgeUnit(props.value.brAge)?.ageUnit || '岁' }
  },
  {
    immediate: true
  }
)
watch(
  () => props.value.admissionCode,
  () => {
    formState.value = { ...props.value, brAge: getAgeUnit(props.value.brAge)?.brAge, ageUnit: getAgeUnit(props.value.brAge)?.ageUnit || '岁' }
  },
  {
    immediate: true
  }
)
watch(
  () => props.value.pyjm,
  () => {
    formState.value = { ...props.value, brAge: getAgeUnit(props.value.brAge)?.brAge, ageUnit: getAgeUnit(props.value.brAge)?.ageUnit || '岁' }
  },
  {
    immediate: true
  }
)
watch(
  () => formState.value,
  (val) => {
    emit('update:value', { ...props.value, ...val, brAge: getAgeUnit(props.value.brAge)?.brAge, ageUnit: getAgeUnit(props.value.brAge)?.ageUnit || '岁' })
  },
  { deep: true }
)

const showConfig = ref({})
const getShowConfig = async () => {
  const { data, mes, code } = await post('/operation/opex/getPatientlnfoList', {
    managementType: '1'
  })
  if (code !== 0) return message.error(mes || '获取数据失败')
  const childrenArray = data.map((item) => item.children).flat()
  childrenArray.forEach((child) => {
    showConfig.value[child.patientInfoName] = child.status === 0
  })
  setTimeout(() => {
    loading.value = false
    emit('loaded')
  }, 100)
}
const onSelectEmployee = (key, select) => {
  formState.value[key + 'Name'] = select.empName
  formState.value[key] = select.empId
}

const generatedZyh = async () => {
  if (!props.value.brId) return message.error('请选择患者')
  const { data, code } = await post('/inp/zydj/getZyh', { brId: props.value.brId })
  if (code !== 0) return message.error('获取住院号失败')
  formState.value = { ...props.value, admissionCode: data }
}
onMounted(() => {
  getShowConfig()
  //排除的字段
  props.excludeItem.forEach((key) => {
    showConfig.value[key] = false
  })
})
const getPinyin = async (name) => {
  const { data, code } = await post('/common/util/getPinyin', { name })
  code === 0 && (formState.value.pyjm = data)
}
defineExpose({
  getData: () => formState.value
})
</script>
<style lang="less" scoped></style>
